﻿using DbModel.Models;
using IRepositories;
using IRepositories.Base;
using IServices;
using Services.Base;

namespace Services
{
    public class ArticleService : BaseServices<Article>, IArticleService
    {
        private readonly IArticleRepository _articleRepository;

        //public ArticleService(IArticleRepository articleRepository):base(articleRepository)
        //{
        //}

        public ArticleService(IBaseRepository<Article> repository, IArticleRepository articleRepository) : base(repository)
        {
            _articleRepository = articleRepository;
        }

        public async Task AddArticleCollection(int id, int userId, CancellationToken cancellationToken = default)
        {
            var article = await _articleRepository.GetByIdAsync(id, cancellationToken);
            article.CollectionArticles.Add(new UserCollectionArticle { UserId = userId, ArticleId = id });
            await _articleRepository.UpdateAsync(article, true, cancellationToken);
        }

        public async Task AddArticleComments(int id, int userId, string Content, CancellationToken cancellationToken = default)
        {
            var article = await _articleRepository.GetByIdAsync(id, cancellationToken);
            article.ArticleComments.Add(new ArticleComment
            {
                Content = Content,
                CreateTime = DateTime.Now,
                CreateUserId = userId
            });
            await _articleRepository.UpdateAsync(article, true, cancellationToken);
        }

        public async Task AdditionalItemAsync(Article article, bool v, int n = 0)
        {
            article.CreateTime = DateTime.Now.AddDays(-n);
            await _articleRepository.InsertAsync(article, true);
        }

        public async Task<Article> GetArticleDetailAsync(int id, CancellationToken cancellationToken = default)
        {
            var entity = await _articleRepository.GetByIdAsync(id, cancellationToken);
            entity.Traffic += 1;
            await _articleRepository.UpdateAsync(entity, true, cancellationToken);
            return entity;
        }

        public Task<Article> GetByIdAsync(int id, CancellationToken cancellationToken = default)
        {
            return _articleRepository.GetByIdAsync(id, cancellationToken);
        }
    }
}
